package com.ymx.darling.executor;

import com.ymx.darling.bean.sql.BoundSql;
import com.ymx.darling.bean.sql.Statement;
import com.ymx.darling.build.Configuration;
import com.ymx.darling.cursor.Cursor;
import com.ymx.darling.exception.ExceptionFactory;
import com.ymx.darling.executor.statement.PreparedStatementHandler;
import com.ymx.darling.log.jdbc.ConnectionLogger;
import com.ymx.darling.transaction.Transaction;

import java.sql.*;
import java.util.Collections;
import java.util.List;

/**
 * @author 爱Java的小于
 */
public class SimpleExecutor implements Executor{
    protected final Transaction transaction;

    public SimpleExecutor(Transaction transaction) {
        this.transaction = transaction;
    }

    /**
     * 为预编译sql设置占位符参数并返回PreparedStatement
     *
     * @param statementHandler 语句处理器
     * @return PreparedStatement
     */
    private PreparedStatement preparedStatement(PreparedStatementHandler statementHandler, Statement statement) {
        Connection connection = this.getConnection(statement);
        BoundSql boundSql = statement.getBoundSql();
        try {
            PreparedStatement preparedStatement = statementHandler.preparedStatement(connection);
            statementHandler.setParameters(preparedStatement, boundSql.getBindParameters());
            return preparedStatement;
        } catch (SQLException exception) {
            String errTitle = "构建PreparedStatement时抛出异常";
            // 抛出异常的时机可能是参数绑定前 所以需要判断空指针异常 如果为null则将绑定前的参数放入异常信息的参数列表
            List<Object> parameters = boundSql.getBindParameters();
            if (parameters == null) {
                Object parameterObject = boundSql.getParameterObject();
                parameters = parameterObject != null ? Collections.singletonList(parameterObject) : Collections.emptyList();
            }
            throw ExceptionFactory.wrapSqlHandleException(errTitle, boundSql.getSql(), parameters, exception);
        }
    }


    /**
     * 当日志开启时返回一个Connection的代理实例
     * @param statement statement
     * @return Connection
     */
    private Connection getConnection(Statement statement) {
        Connection connection = this.transaction.getConnection();
        if (statement.getLogger().isDebugEnabled()) {
            connection = ConnectionLogger.newInstance(connection, statement);
        }
        return connection;
    }


    /**
     * 创建StatementHandler实例
     * @param statement statement
     * @return StatementHandler
     */
    private PreparedStatementHandler createStatementHandler(Statement statement) {
        Configuration configuration = statement.getConfiguration();
        return configuration.createStatementHandler(statement);
    }


    @Override
    public <T> List<T> queryList(Statement statement) {
        PreparedStatementHandler statementHandler = this.createStatementHandler(statement);
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = this.preparedStatement(statementHandler, statement);
            return statementHandler.queryList(preparedStatement);
        } catch (SQLException exception) {
            String errorTitle = "数据库执行查询时抛出异常";
            BoundSql boundSql = statement.getBoundSql();
            throw ExceptionFactory.wrapSqlHandleException(errorTitle, boundSql.getSql(), boundSql.getBindParameters(), exception);
        } finally {
            statementHandler.close(preparedStatement);
        }
    }


    public <T> Cursor<T> queryCursor(Statement statement){
        PreparedStatementHandler statementHandler = this.createStatementHandler(statement);
        PreparedStatement preparedStatement = this.preparedStatement(statementHandler, statement);
        return statementHandler.queryCursor(preparedStatement);
    }


    @Override
    public int update(Statement statement) {
        PreparedStatementHandler statementHandler = this.createStatementHandler(statement);
        PreparedStatement preparedStatement = this.preparedStatement(statementHandler, statement);
        try {
            return statementHandler.update(preparedStatement);
        } catch (SQLException exception) {
            String errorTitle = "数据库执行更新操作时抛出异常";
            BoundSql boundSql = statement.getBoundSql();
            throw ExceptionFactory.wrapSqlHandleException(errorTitle, boundSql.getSql(), boundSql.getBindParameters(), exception);
        } finally {
            statementHandler.close(preparedStatement);
        }
    }


    @Override
    public Connection getConnection(){
        return this.transaction.getConnection();
    }


    @Override
    public boolean isClose() {
        return this.transaction.isClose();
    }


    @Override
    public void close() {
        this.transaction.close();
    }


    @Override
    public void rollBack() {
        this.transaction.rollBack();
    }


    @Override
    public void commit() {
        this.transaction.commit();
    }
}
